package com.oyjd.framework.util.del;

import java.io.File;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;

import com.oyjd.framework.log.MyLog;

/**
 * 删除图片库
 * 
 * @author 欧建东
 * @email oyjd@163.com
 * 
 */
public class DelImgs {
	private static final String TAG = "DelImgs";

	/**
	 * 删除图片库
	 * 
	 * @param activity
	 */
	public static boolean del(Context context) {
		boolean flag = false;
		try {
			// 清除数据库记录对应的图片
			delDb(context);
			// 清除缓存目录
			delCache();
			flag = true;
			MyLog.i(TAG, "删除图片库成功！");
		} catch (Exception err) {
			MyLog.e(TAG, "删除图片库失败！", err);
		}
		return flag;
	}

	/**
	 * 清除数据库记录对应的图片
	 * 
	 * @param activity
	 */
	private static void delDb(Context context) {
		String uri = "content://media/external/images/media";
		ContentResolver cr = context.getContentResolver();
		Cursor c = cr.query(Uri.parse(uri), null, null, null, null);
		if (c != null) {
			while (c.moveToNext()) {
				int id = c.getInt(c.getColumnIndex(MediaStore.Images.ImageColumns._ID));
				String path = c.getString(c.getColumnIndex(MediaStore.Images.ImageColumns.DATA));
				new File(path).delete();
				// 注意：1.6版本只支持这种删除方式且一次只能删一条，其他where 或整体删除方式均报错
				String delUri = uri + File.separator + id;
				cr.delete(Uri.parse(delUri), null, null);
				MyLog.d(TAG, "删除图片：id->" + id + " path->" + path);
			}
			c.close();
		}
	}

	/**
	 * 清除缓存目录
	 */
	private static void delCache() {
		String sdcardDir = Environment.getExternalStorageDirectory().getPath();
		String[] path = { "/Android/data/com.cooliris.media", "/DCIM/.thumbnails" };
		for (String s : path) {
			dealFile(new File(sdcardDir + s));
		}
	}

	/**
	 * 目录迭代删除
	 * 
	 * @param f
	 */
	private static void dealFile(File f) {
		if (f.exists())
			for (File fs : f.listFiles()) {
				if (fs.isFile()) {
					fs.delete();
				} else if (fs.isDirectory()) {
					dealFile(fs);
				}
			}
	}

}